package org.example.mq;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.config.RabbitMQConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class MessageListener {
    // 重试的时间间隔。
    private int[] delayTime = {0,15000,30000,60000,300000};
    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "sms_inter")
    public void consume(String report, Channel channel, Message message)
            throws IOException {

        log.info(report);
        //isSendMessage(report);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        return;

    }

    private void isSendMessage(String report) {

        rabbitTemplate.convertAndSend(RabbitMQConfig.DELAYED_EXCHANGE, "",  report, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                             // 设置延迟时间
                        message.getMessageProperties().setDelay(delayTime[Integer.parseInt(report)+1]);
                        return message;
                    }
                });

    }

    /**
     * 监听延迟交换机路由过来的消息
     * @param report
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues = RabbitMQConfig.DELAYED_QUEUE)
    public void delayedConsume(String report, Channel channel,Message
            message) throws IOException {

// 2、判断状态报告发送情况
        isSendMessage(report);
// 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
